package org.example;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.example.handler.EchoServerHandler;

import java.net.InetSocketAddress;

/**
 * Hello world!
 */
public class EchoServer {
    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        if (args.length != 1) {
            System.out.println("Usage：" + EchoServer.class.getSimpleName() + "<port>");
        }
        int port = Integer.parseInt(args[0]);
        new EchoServer(port).start();
    }

    public void start() throws InterruptedException {
        final EchoServerHandler serverHandler = new EchoServerHandler();
        NioEventLoopGroup group = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(group)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(port))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // EchoServerHandler 被标注为@Shareable，所以我们可以总是使用同样的实例
                        socketChannel.pipeline().addLast(serverHandler);
                    }
                });
        //serverBootstrap都是异步操作，需要使用sync同步阻塞（绑定本机服务器端口）
        ChannelFuture sync = serverBootstrap.bind().sync();
        // 获取Channel 的CloseFuture ，并阻塞到当前线程完成
        sync.channel().closeFuture().sync();

        // 关闭线程池资源
        group.shutdownGracefully().sync();
    }
}
